package com.mobile.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mobile.util.config.CommonResultStatus;
import com.mobile.util.config.exception.BusinessException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.Optional;


/**
 * @ClassName: JwtUtil
 * @Description: jwt工具类
 * @Date: 2020/9/25
 * @Author: cheetah
 * @Version: 1.0
 */
public class JwtUtil {
    private  static Logger logger = LogManager.getLogger(JwtUtil.class);

    //JWT-account
    public static final String ACCOUNT = "username";

    //JWT-currentTimeMillis
    public final static String CURRENT_TIME_MILLIS = "currentTimeMillis";
    //有效期时间2小时
    public static final long EXPIRE_TIME = 8 * 60 * 60 * 1000L;       //2hour
    public static final long CONTINUE_TIME =  30 * 60L;       //续期阈值 30min
//    public static final long EXPIRE_TIME = 20 * 1000L;      //20s

    public static final String SECRET_KEY = "kcdz***mes@appKey";


    /**
     * 生成签名
     *
     * @param account
     * @param currentTimeMillis
     * @return
     */
    public static String sign(String account, String currentTimeMillis) {
        // 帐号加JWT私钥加密
        String secret = account + SECRET_KEY;
        // 此处过期时间，单位：毫秒
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);

        return JWT.create()
                .withClaim(ACCOUNT, account)
                .withClaim(CURRENT_TIME_MILLIS, currentTimeMillis)
                .withExpiresAt(date)
                //创建一个新的JWT，并使用给定的算法进行标记
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        String userCode = getClaim(token, ACCOUNT);
        String key = userCode + "-" + Const.USER_TOKEN + "-" + token;
        //验证redis中token是否过期/销毁
        Jedis jedis = RedisUtil.getJedis();
        Long ttl = jedis.ttl(key);
        if (Optional.ofNullable(jedis.get(key)).isPresent()) {
            logger.info("认证通过："+token);
            logger.info("account:" + getClaim(token, ACCOUNT));
            logger.info("到期时间：" + DateUtil.date2Str(new Date(System.currentTimeMillis()+(ttl * 1000))));
            //token剩余时间小于三十分钟-自动续期
            if (ttl < CONTINUE_TIME) {
                jedis.expireAt(key,(System.currentTimeMillis()+EXPIRE_TIME)/1000);
                logger.info("token续期成功，到期时间：" + DateUtil.date2Str(new Date(System.currentTimeMillis()+(jedis.ttl(key) * 1000))));
            }
            jedis.close();
            return true;
        }else{
            jedis.close();
        }
        throw new BusinessException(CommonResultStatus.LOGIN_ERROR);

    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     *
     * @param token
     * @param claim
     * @return
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}

